-module(cloap_api).
-include("cloap_record.hrl").
-export([
         start_spider/1,
         fetch/1, 
         refresh/1
        ]).

start_spider(Who) ->
    case pdict_store:userinfo_get(Who, pid) of
        not_found ->
            {ok, Pid} = spider_thread_sup:start_child(Who, 3600),
            pdict_store:userinfo_put(Who, pid, Pid),
            {ok, Pid};
        ExistPid -> {ok, ExistPid}
    end.

fetch(Who) ->
    spider_call(Who, fetch).
refresh(Who) ->
    spider_call(Who, refresh_sync).

spider_call(Who, Method) ->
    case pdict_store:userinfo_get(Who, pid) of
        not_found ->
            start_spider(Who),
            spider_call(Who, Method);
        Pid -> 
            erlang:apply(spider_thread, Method, [Pid])
    end.
    
